package com.jigoucai.module;

import com.jigoucai.bean.biz.CashAccount;
import com.jigoucai.bean.dict.Dict;
import com.jigoucai.bean.param.req.finance.*;
import com.jigoucai.bean.param.resp.BaseResp;
import com.jigoucai.entity.finance.Current;
import com.jigoucai.entity.finance.Fund;
import com.jigoucai.entity.user.User;
import com.jigoucai.util.Code;
import com.jigoucai.util.JgcUtil;
import com.jigoucai.util.Util;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.*;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2018/3/25
 *
 * @author Jianghao(howechiang @ gmail.com)
 */
@IocBean
@Fail("http:500")
@At("/finance")
public class FinanceModule extends BaseModule {

    /**
     * 申请提现
     *
     * @param req
     * @return
     */
    @POST
    @At("/withdraw")
    @Ok("json")
    @AdaptBy(type = JsonAdaptor.class)
    public BaseResp withdraw(WithdrawReq req) {
        try {
            if (Strings.isBlank(req.getBankName())) {
                return Code.resp("USER_PARAMTER_MISSING", "提现方式");
            } else if (req.getAmount() < 1) {
                return Code.resp("SYS_PARAMTER_FORMAT_ERROR", "提现金额");
            } else if (req.getAmount() > financeService.getFund(req.getUserId())) {
                return Code.resp("USER_BALANCE_INSUFFICIENT");
            } else {
                User user = dao.fetch(User.class, req.getUserId());
                Current current = new Current();
                current.setAmount(-(int) (req.getAmount() * 100));
                current.setCurrentNum(JgcUtil.generateTradeNo("FC"));
                current.setEntryTime(Times.now());
                current.setArrived(false);
                current.setShroffAccount(user.getCashAccounts().get(0));
                current.setPaymentAccount(Dict.JDG_DEFAULT_PAYMENT_ACCOUNT_ALIPAY);
                current.setReason("用户提现");
                current.setUserId(user.getUserId());
                current.setCause(false);
                current.setTsn(null);
                Fund fund = new Fund();
                fund.setAmount(-(int)(req.getAmount() * 100));
                fund.setCause(false);
                fund.setBillTime(Times.now());
                fund.setReason("提现冻结");
                fund.setFundNum(JgcUtil.generateTradeNo("FF"));
                fund.setUserId(user.getUserId());
                Trans.exec(new Atom() {
                    public void run() {
                        dao.insert(current);
                        fund.setRelateId(current.getCurrentId());
                        fund.setRelate(Lang.obj2nutmap(current));
                        dao.insert(fund);
                    }
                });
                return JgcUtil.buildSuccessResp("已提交提现申请，请等待系统处理");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Code.resp("SYS_ERROR");
        }
    }

    /**
     * 提现帐户维护
     *
     * @param req
     * @return
     */
    @POST
    @At("/maintain")
    @Ok("json:full")
    @AdaptBy(type = JsonAdaptor.class)
    public BaseResp maintain(MaintainReq req) {

        try {
            User user = dao.fetch(User.class, req.getUserId());
            if (Strings.isBlank(req.getPayPassword())) {
                return Code.resp("USER_PARAMTER_MISSING", "支付密码");
            } else if (!Strings.equalsIgnoreCase(user.getPayPassword(), Lang.sha1(user.getUserId() + req.getPayPassword()))) {
                return Code.resp("USER_PAYPASSWORD_IS_ERROR");
            } else if (!Strings.equalsIgnoreCase("支付宝", req.getBankName())) {
                return Code.resp("SYS_NOT_SUPPORT", "提现方式", "支付宝");
            } else if (Strings.isBlank(req.getAccount())) {
                return Code.resp("USER_PARAMTER_MISSING", "提现帐户");
            } else if (!Strings.isMobile(req.getAccount()) && !Strings.isEmail(req.getAccount())) {
                return Code.resp("SYS_PARAMTER_FORMAT_ERROR", "提现帐户");
            } else if (!user.isAuth()) {
                return Code.resp("USER_UNAUTHENTICATED");
            } else {
                CashAccount cashAccount = new CashAccount();
                cashAccount.setAccount(req.getAccount());
                cashAccount.setBankName(req.getBankName());
                cashAccount.setAccountName(user.getRealname());
                cashAccount.setDefault(true);
                List<CashAccount> list = new ArrayList<>();
                list.add(cashAccount);
                user.setCashAccounts(list);
                dao.update(user, "^(cashAccounts)$");
                return JgcUtil.buildSuccessResp("提现帐户维护成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Code.resp("SYS_ERROR");
        }
    }

    /**
     * 余额明细表
     *
     * @param req
     * @return
     */
    @POST
    @At("/fundList")
    @Ok("json")
    @AdaptBy(type = JsonAdaptor.class)
    public BaseResp fundList(FundListReq req) {
        try {
            QueryResult result = query(Fund.class, Cnd.where("userId", "=", req.getUserId()),
                    Util.defaultPager(req.getPageNumber(), req.getPageSize()));
            return JgcUtil.buildSuccessResp(new NutMap().setv("list", result.getList(Fund.class))
                    .setv("pager", result.getPager())
                    .setv("total", financeService.getFund(req.getUserId())));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Code.resp("SYS_ERROR");
        }
    }

    /**
     * 资金流水表
     *
     * @param req
     * @return
     */
    @POST
    @At("/currentList")
    @Ok("json")
    @AdaptBy(type = JsonAdaptor.class)
    public BaseResp currentList(CurrentListReq req) {
        try {
            QueryResult result = query(Current.class, Cnd.where("userId", "=", req.getUserId()),
                    Util.defaultPager(req.getPageNumber(), req.getPageSize()));
            return JgcUtil.buildSuccessResp(new NutMap().setv("list", result.getList(Current.class))
                    .setv("pager", result.getPager()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Code.resp("SYS_ERROR");
        }
    }

    /**
     * 余额查询
     *
     * @param req
     * @return
     */
    @POST
    @At("/queryFund")
    @Ok("json:full")
    @AdaptBy(type = JsonAdaptor.class)
    public BaseResp queryFund(QueryFundReq req) {
        try {
            return JgcUtil.buildSuccessResp(new NutMap().setv("myFund", financeService.getFund(req.getUserId())));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Code.resp("SYS_ERROR");
        }
    }
}
